﻿using demo;
using Flee.PublicTypes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LogicClass
{
    /// <summary>
    /// 表达式计算的类
    /// </summary>
    public class Logic : ActionItem
    {
        private IGenericExpression<bool> bGeneric;

        public Logic() : base()
        {
            VarAlias = new List<string>();
            IsLogic = true;//这是为了属性控件当中显示文本内容属性
        }

        public List<string> VarAlias { get; set; }

        /// <summary>
        /// 表达式内容
        /// </summary>
        [Browsable(true), Editor(typeof(propertyLogicEdit), typeof(UITypeEditor))]
        public string BoolExpression { get; set; }

        public override bool Initilize()
        {
            Stopwatch sw = Stopwatch.StartNew();
            //1,创建上下文类
            ExpressionContext context = new ExpressionContext();
            //2,引用类型
            context.Imports.AddType(typeof(Math));
            //3准备变量
            foreach (var guid in VarIDs)
            {
                var varInfo = GlobalVars.Ins.GetVar(guid);
                if (varInfo != null)
                {
                    context.Variables[varInfo.Name] = varInfo.Value;
                }
            }


            //4,编译
            bGeneric = context.CompileGeneric<bool>(BoolExpression);
            Em.GetEvent<DebugMessage>().Publish($"编译{ItemName}成功 耗时{sw.ElapsedMilliseconds}");
            return true;
        }

        protected override bool RunMethod()
        {
            if (bGeneric == null)
            {
                Initilize();
            }
            //5,执行
            bool result = false;
            try
            {
                result = bGeneric.Evaluate();
                Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}={result}");

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}失败\r {e.Message}");
            }


            return result;
        }
    }

    /// <summary>
    ///propertygrid 表达式的自定义属性弹窗输入功能 必须继承该类，因为所有的propertygrid都是直接或间接继承自该类
    /// </summary>
    public class propertyLogicEdit : UITypeEditor
    {
        /// <summary>
        /// 指定为模式窗体属性编辑器类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {

            return UITypeEditorEditStyle.DropDown;//Modal为省略号类型，DropDown为下拉列表
        }

        /// <summary>
        /// 打开属性编辑器修改数据 可指定文件路径 可弹窗 只要实现该方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {

            return LogicFrm.EditValue(value);
        }
    }

    [ReflectAble]
    public class IfItem : Logic
    {
        private int _currentIndex;

        [Browsable(false), JsonIgnore]
        public bool Completed { get; set; }
       
        protected override void NextActionItemIndex(bool result)
        {


            
                int sum = 0;//用来记录嵌套次数
                //查找所有分支，赋值MyIf
                for (int i = CurrentIndex + 1; i < this.Flow.ActionItems.Count - 1; i++)
                {
                    ActionItem nextItem = this.Flow.ActionItems[i];
                    //查找If嵌套
                    if (nextItem.GetType() == typeof(IfItem))
                    {
                        sum += 1; //嵌套+1
                    }
                    if (nextItem.GetType() == typeof(EndIfItem))
                    {
                        if (sum == 0)
                        {
                            break;//找到Endif就没必要继续搜索下去了
                        }
                        sum -= 1;//嵌套-1
                    }

                    if (sum == 0)//如果没有嵌套
                    {
                        if (nextItem is ElseIfItem elseifItem)
                        {
                            elseifItem.IfItem = this;
                        }
                        if (nextItem is ElseItem elseItem)
                        {
                            elseItem.IfItem = this;
                        }
                    }
                }
            
            if (result)
            {
               //Flow.NextIndex++;
                Completed = true;
            }
            else
            {
                Completed = false;
                int sum1 = 0;//用来记录嵌套次数
                            //查找ElseIF
                for (int i = CurrentIndex + 1; i < this.Flow.ActionItems.Count; i++)
                {
                    ActionItem nextItem = this.Flow.ActionItems[i];
                    //查找If嵌套
                    if (nextItem.GetType() == typeof(IfItem))
                    {
                        sum1 += 1; //嵌套+1
                    }
                    if (nextItem.GetType() == typeof(EndIfItem))
                    {
                        if (sum1 == 0)
                        {
                            if (nextItem.GetType() == typeof(EndIfItem))
                            {
                                //this.Flow.NextIndex = i;
                                return;
                            }
                        }
                        sum1 -= 1;//嵌套-1
                    }

                    if (sum1 == 0)//如果没有嵌套
                    {
                        if (nextItem.GetType() == typeof(ElseIfItem))
                        {
                            //this.Flow.NextIndex = i;
                            return;
                        }

                        if (nextItem.GetType() == typeof(ElseItem))
                        {
                            //this.Flow.NextIndex = i;
                            return;
                        }

                    }
                }
            }


        }


    }
    [ReflectAble]
    public class ElseIfItem : Logic
    {
        [Browsable(false), JsonIgnore]
        public IfItem IfItem { get; set; }
    }
    [ReflectAble]
    public class ElseItem : ActionItem
    {
        [Browsable(false), JsonIgnore]
        public IfItem IfItem { get; set; }
        

        protected override bool RunMethod()
        {
            return true;
        }

        protected override void NextActionItemIndex(bool result)
        {
            if (IfItem.Completed)//如果已经执行过一个分支,就跳到EndIf
            {
                int sum = 0;//用来记录嵌套次数
                //查找ElseIF
                for (int i = CurrentIndex + 1; i < Flow.ActionItems.Count; i++)
                {
                    ActionItem nextItem = Flow.ActionItems[i];
                    //查找If嵌套
                    if (nextItem.GetType() == typeof(IfItem))
                    {
                        sum += 1; //嵌套+1
                    }
                    if (nextItem.GetType() == typeof(EndIfItem))
                    {
                        if (sum == 0)//如果没有嵌套
                        {
                            //Flow.NextIndex = i;//EndIf
                            return;
                        }
                        sum -= 1;//嵌套-1
                    }
                }
            }
            else
            {
                //Flow.NextIndex++;//如果没有进入过某个分支，就执行Else 的下一句
            }
        }
    }
    [ReflectAble]
    public class EndIfItem : ActionItem
    {
        [Browsable(false), JsonIgnore]
        public IfItem IfItem { get; set; }
       

        protected override bool RunMethod()
        {
            return true;
        }

    }
    [ReflectAble]


    public class WhileItem : Logic
    {
        protected override void NextActionItemIndex(bool result)
        {
            {
                int sum = 0;//用来记录嵌套次数
                //查找所有分支，赋值MyWhile
                for (int i = CurrentIndex + 1; i < Flow.ActionItems.Count - 1; i++)
                {
                    ActionItem nextItem = Flow.ActionItems[i];
                    //查找If嵌套
                    if (nextItem.GetType() == typeof(WhileItem))
                    {
                        sum += 1; //嵌套+1
                    }
                    if (nextItem.GetType() == typeof(EndWhileItem))
                    {
                        if (sum == 0)
                        {
                            var endwhile = (EndWhileItem)nextItem;
                            endwhile.MyWhile = this;
                            break;//找到ActionEndWhile就没必要继续搜索下去了
                        }
                        sum -= 1;//嵌套-1
                    }

                    if (sum == 0)//如果没有嵌套
                    {
                        if (nextItem is BreakItem elseifItem)
                        {
                            elseifItem.MyWhile = this;
                        }
                        if (nextItem is ContinueItem elseItem)
                        {
                            elseItem.MyWhile = this;
                        }
                    }
                }
            }

            if (result) //表达式结果为True,执行While的下一句
            {
                //Flow.NextIndex++;
            }
            else //表达式为false，执行Endwhile下一句
            {
                //查找EndWhile
                int sum = 0;//用来记录嵌套次数
                for (int i = CurrentIndex + 1; i < Flow.ActionItems.Count; i++)
                {
                    var nextItem = Flow.ActionItems[i];
                    //查找while嵌套
                    if (nextItem.GetType() == typeof(WhileItem))
                    {
                        sum += 1; //嵌套+1
                    }
                    if (nextItem.GetType() == typeof(EndWhileItem))
                    {
                        if (sum == 0)
                        {
                            //Flow.NextIndex = i + 1;//找到EndWhile下一行
                            return;
                        }
                        sum -= 1;//嵌套-1
                    }
                }
            }
        }
    }

    [ReflectAble]
    public class ContinueItem : ActionItem
    {
        [Browsable(false), JsonIgnore]
        public WhileItem MyWhile { get; set; }

        protected override bool RunMethod()
        {
            return true;
        }

        protected override void NextActionItemIndex(bool result = true)
        {
            int sum = 0;//用来记录嵌套次数
            //查找往前找While
            for (int i = CurrentIndex - 1; i > -1; i--)
            {
                var nextItem = Flow.ActionItems[i];
                //查找If嵌套
                if (nextItem.GetType() == typeof(EndWhileItem))
                {
                    sum += 1; //嵌套+1
                }
                if (nextItem.GetType() == typeof(WhileItem))
                {
                    sum -= 1;//嵌套-1
                }
                if (sum == 0)//如果没有嵌套
                {
                    if (nextItem.GetType() == typeof(WhileItem))
                    {
                        //Flow.NextIndex = i;
                        return;
                    }
                }
            }
        }
    }

    [ReflectAble]
    public class BreakItem : ActionItem
    {
        [Browsable(false), JsonIgnore]
        public WhileItem MyWhile { get; set; }

        protected override bool RunMethod()
        {
            return true;
        }

        protected override void NextActionItemIndex(bool result = true)
        {
            int sum = 0;//用来记录嵌套次数
            //查找ElseIF
            for (int i = CurrentIndex + 1; i < Flow.ActionItems.Count; i++)
            {
                var nextItem = Flow.ActionItems[i];
                //查找If嵌套
                if (nextItem.GetType() == typeof(WhileItem))
                {
                    sum += 1; //嵌套+1
                }
                if (nextItem.GetType() == typeof(EndWhileItem))
                {
                    if (sum == 0)//如果没有嵌套
                    {
                        //Flow.NextIndex = i + 1;
                        return;
                    }
                    sum -= 1;//嵌套-1
                }
            }
        }
    }

    [ReflectAble]
    public class EndWhileItem : ActionItem
    {
        [Browsable(false), JsonIgnore]
        public WhileItem MyWhile { get; set; }

        protected override bool RunMethod()
        {
            return true;
        }

        protected override void NextActionItemIndex(bool result = true)
        {
            int sum = 0;//用来记录嵌套次数
            //查找往前找While
            for (int i = CurrentIndex - 1; i > -1; i--)
            {
                var nextItem = Flow.ActionItems[i];
                //查找If嵌套
                if (nextItem.GetType() == typeof(EndWhileItem))
                {
                    sum += 1; //嵌套+1
                }
                if (nextItem.GetType() == typeof(WhileItem))
                {
                    if (sum == 0) //如果没有嵌套
                    {
                        if (nextItem.GetType() == typeof(WhileItem))
                        {
                            //Flow.NextIndex = i;
                            return;
                        }
                    }

                    sum -= 1;//嵌套-1
                }
                if (sum == 0)//如果没有嵌套
                {
                    if (nextItem.GetType() == typeof(WhileItem))
                    {
                        //Flow.NextIndex = i;
                        return;
                    }
                }
            }
        }
    }
}
